<template>
    <div>微信登录</div>
</template>

<script>
const appid = "wx3bdb1192c22883f3"
const secret = "db9d6b88821df403e5ff11742e799105"
import axios from "axios"
import auth from "~/utils/auth"
export default {
    asyncData(context) {
        //context.params == 获取所有地址参数
        //context.query  == 获取所有请求参数
        let code = context.query.code
        // console.log(code)
        let access_toke_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
        return axios.get(access_toke_url).then(res => {
            //console.log(res.data)
            let access_token = res.data.access_token
            let openid = res.data.openid
            let info_url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`
            return axios.get(info_url).then(res2 => {
                //console.log(res2.data)
                return {
                    user:{
                        name:res2.data.nickname,
                        avatar:res2.data.headimgurl,
                        token:access_token
                    }
                }
            })
        })
    },
    mounted () {
        if(this.user != undefined && this.user != null) {
            auth.setUser(this.user);
            location.href="/"
        }
    }
}
</script>

<style>

</style>
